package com.zone.vehicle.superApps.view.home.app.detail;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.zone.lib.download.DownloadConstant;
import com.zone.lib.download.DownloadStatus;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.sdk.module.appstore.entity.AppEntity;
import com.zone.sdk.module.comment.entity.ReplyEntity;
import com.zone.vehicle.superApps.databinding.FragmentAppDetailBinding;
import com.zone.vehicle.superApps.model.HomeViewModel;
import com.zone.vehicle.superApps.model.ViewModelFactory;
import com.zone.vehicle.superApps.view.common.HandledFragment;
import com.zone.vehicle.superApps.view.home.app.adapter.CommentDialogSingleAdapter;
import com.zone.vehicle.superApps.view.home.app.detail.widget.VerticalCommentLayout;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

public class AppDetailFragment extends HandledFragment implements VerticalCommentLayout.CommentItemClickListener, BaseQuickAdapter.RequestLoadMoreListener{

    private static final String TAG = AppDetailFragment.class.getSimpleName();

    private FragmentAppDetailBinding binding;

    private HomeViewModel viewModel;

    private CommentDialogSingleAdapter bottomSheetAdapter;

    @Override
    public void onCreate(@org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = FragmentAppDetailBinding.inflate(inflater);
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(HomeViewModel.class);
        initView();
        initData();
        return binding.getRoot();
    }

    private void testA(){
        DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().deleteAll();
    }

    private void initView(){
        binding.btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "AppDetailFragment btnBack onClick");
                onBack();
            }
        });

        viewModel.getCurrentApp().observe(getViewLifecycleOwner(), new Observer<AppEntity>() {
            @Override
            public void onChanged(AppEntity appEntity) {
                if (ObjectUtils.isNotEmpty(appEntity)){
                    binding.name.setText(appEntity.getName());
                    binding.producer.setText(appEntity.getProducer());
//                binding.pic.setImageResource(R.drawable.app_pic_demo);
//                Glide.with(holder.itemView.getContext()).asBitmap().load(app2.getPreviews()).apply(options).into(holder.pic2);
                    //设置图片大小
                    RoundedCorners roundedCorners = new RoundedCorners(50);
                    //扩展功能
                    RequestOptions options = RequestOptions.bitmapTransform(roundedCorners)
                            .placeholder(new ColorDrawable(Color.GRAY));//设置占位图
                    Glide.with(requireContext())
                            .asBitmap().load(appEntity.getImages())
                            .apply(options).into(binding.pic);
//                binding.pic.setImageResource(R.drawable.app_pic_demo);
                    Glide.with(requireContext())
                            .asBitmap().load(appEntity.getScreenshot())
                            .apply(options).into(binding.screenshotImg);

                    Glide.with(requireContext())
                            .asBitmap().load(appEntity.getIcon())
                            .apply(options).into(binding.icon);

                    binding.score.setText(appEntity.getScore());
                    binding.desc.setText(appEntity.getDesc());

                    String downloadTxt = "下载 （";
                    if (StringUtils.isNotEmpty(appEntity.getSize())){
                        downloadTxt += appEntity.getSize();
                    }
                    downloadTxt += ")";
//                    binding.btnDownload.setText(downloadTxt);
                    binding.producer2.setText(appEntity.getProducer());
                    binding.officialGroup.setText(appEntity.getOfficialGroup());
                    binding.version.setText(appEntity.getVersion());
                    binding.size.setText(appEntity.getSize());
                    binding.updateTime.setText(appEntity.getUpdateTime());
                    binding.netProtocol.setText(appEntity.getNetProtocol());
                    binding.adaptiveModel.setText(appEntity.getAdaptiveModel());
                    binding.oneWord.setText(appEntity.getOneWord());
                    binding.producer3.setText(appEntity.getProducer());
                }
            }
        });

        //评论
        binding.commentLayout.setHasFixedSize(true);
        binding.commentLayout.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.commentLayout.setItemAnimator(new DefaultItemAnimator());
        bottomSheetAdapter = new CommentDialogSingleAdapter(this);
        bottomSheetAdapter.setLoadMoreView(new SimpleLoadMoreView());
        bottomSheetAdapter.setOnLoadMoreListener(this, binding.commentLayout);
        binding.commentLayout.setAdapter(bottomSheetAdapter);
        viewModel.getCurrentCommentList().observe(getViewLifecycleOwner(), commentEntityCommentPage -> {
            bottomSheetAdapter.setNewData(commentEntityCommentPage.getDataList());
        });
        viewModel.getCommentScore().observe(getViewLifecycleOwner(), appCommentScoreEntity -> {
            binding.averageScore.setText(""+appCommentScoreEntity.getAverageScore());
            binding.commentCount.setText(""+appCommentScoreEntity.getCommentCount()+" 人评分");
            try {
                binding.line5.setProgress(appCommentScoreEntity.getFiveScore());
                binding.line4.setProgress(appCommentScoreEntity.getFourScore());
                binding.line3.setProgress(appCommentScoreEntity.getThreeScore());
                binding.line2.setProgress(appCommentScoreEntity.getTwoScore());
                binding.line1.setProgress( appCommentScoreEntity.getOneScore());
            }catch (Exception e){
                e.printStackTrace();
            }
        });

//        binding.downloadProgress.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!binding.downloadProgress.isFinish()){
//                    binding.downloadProgress.toggle();
//                    if (binding.downloadProgress.isStop()) {
//                        //继续下载
//                        viewModel.downLoadApp(getContext(), DownloadStatus.PREPARE_DOWNLOAD);
////                        viewModel.downLoadApp2(getContext(), DownloadStatus.PREPARE_DOWNLOAD);
//                    } else {
//                        //暂停
//                        viewModel.downLoadApp(getContext(), DownloadStatus.PAUSE_DOWNLOAD);
////                        viewModel.downLoadApp2(getContext(), DownloadStatus.PAUSE_DOWNLOAD);
////                        viewModel.downLoadApp(getContext(), viewModel.getCurrentApp().getValue());
////                        viewModel.downLoadApp2(getContext());
//                    }
//                }
////                binding.downloadProgress.setProgress(0f);
//
////                binding.btnDownload.setVisibility(View.VISIBLE);
////                viewModel.downLoadApp(getContext(), viewModel.getCurrentApp().getValue());
//            }
//        });

        binding.btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.downLoadApp(getContext(), DownloadStatus.PREPARE_DOWNLOAD);
//                viewModel.installApp(getContext(), "");
            }
        });

    }
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            switch (msg.what){
                case 1:
                    Download download = (Download)msg.obj;
//                    float progress = (float)((download.getDownloadLocation()/download.getTotal())*100);
//                    if (download.getTotal() > 0){
//                        progress = (float)((download.getDownloadLocation()/download.getTotal())*100);
//                    }else {
//                        progress = (float)((downloadProgress.getDownloadPosition()/10000)*100);
//                    }
//                    System.out.println(downloadProgress.getDownloadPosition());
//                    binding.downloadProgress.setProgress(progress);
//                    binding.btnDownload.setVisibility(View.INVISIBLE);
//                    binding.btnDownload.setText(""+download.getDownloadLocation());
                    if (download.getDownloadStatus() == DownloadStatus.LOADING_DOWNLOAD) {
                        if (download.getTotal() > 0) {
                            binding.btnDownload.setVisibility(View.INVISIBLE);
                            int progress = (int)(download.getDownloadLocation() * 100 / download.getTotal());
                            binding.downloadProgress.setProgress(progress);
                        }else {
                            binding.btnDownload.setVisibility(View.VISIBLE);
                        }
                    }else if (download.getDownloadStatus() == DownloadStatus.PAUSE_DOWNLOAD) {
                        binding.downloadProgress.setProgress(0);
                        binding.btnDownload.setText("暂停");
                        binding.btnDownload.setVisibility(View.VISIBLE);
                    }else if (download.getDownloadStatus() == DownloadStatus.WAIT_DOWNLOAD
                            || download.getDownloadStatus() == DownloadStatus.PREPARE_DOWNLOAD) {
                        binding.downloadProgress.setProgress(0);
                        binding.btnDownload.setVisibility(View.VISIBLE);
                        binding.btnDownload.setText("下载准备...");
                    }
                    if (download.getDownloadStatus() == DownloadStatus.COMPLETE_DOWNLOAD){
//                        binding.downloadProgress.finishLoad();
//                        binding.btnDownload.setVisibility(View.VISIBLE);
                        binding.btnDownload.setVisibility(View.VISIBLE);
                        binding.btnDownload.setText("下载完成");
//                        viewModel.installApp(getContext(), downloadProgress.getAppCode());
                    }
                case 2:
                    if (binding.btnDownload.isShown()){
//                        binding.btnDownload.setVisibility(View.GONE);
                    }else {
//                        binding.btnDownload.setVisibility(View.VISIBLE);
                    }
                    break;
            }
            return false;
        }
    });

//        if (!binding.downloadProgress.isFinish()) {
////            binding.downloadProgress.toggle();
//        }else {
//            binding.downloadProgress.reset();
//        }
//        final int[] i = {0};
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                if (i[0] > 100){
//                    System.out.println("timer cancel");
//                    timer.cancel();
//                }
//                i[0]++;
//                DownloadProgress downloadProgress = new DownloadProgress();
//                downloadProgress.setDownloadPosition(Long.valueOf(""+i[0]));
//                downloadProgress.setTotal(100L);
//                Message message = new Message();
//                message.what = 1;
//                message.obj = downloadProgress;
//                handler.sendMessage(message);
//            }
//        }, 1, 100);
//
//    }
//    private void testDownload(){

    @Override
    public void onResume() {
        super.onResume();
        viewModel.getAppDetail();
//        initIDigitalZoneStoreService();
        registerReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
//        stopOfferService();
    }

    private void initData(){

    }

    @Override
    public void onMoreClick(View layout, int position) {

    }

    @Override
    public void onItemClick(View view, ReplyEntity bean, int position) {

    }

    @Override
    public void onLikeClick(View layout, ReplyEntity bean, int position) {

    }

    @Override
    public void onLoadMoreRequested() {

    }

    private void registerReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadConstant.DOWNLOAD_APP_ACTION);
        requireActivity().registerReceiver(receiver, filter);
    }

    private void unregisterReceiver(){
        requireActivity().unregisterReceiver(receiver);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null != intent) {
                Log.e(TAG, "BroadcastReceiver action="+intent.getAction());
                switch (intent.getAction()){
                    case DownloadConstant.DOWNLOAD_APP_ACTION:
                        Download download = (Download) intent.getSerializableExtra(DownloadConstant.EXTRA_INTENT_DOWNLOAD);
                        Log.e(TAG, "BroadcastReceiver download="+download.toString());
                        Message message = new Message();
                        message.what = 1;
                        message.obj = download;
                        handler.sendMessage(message);
                        break;
                }
            }
        }
    };
}